package cn.zhangfusheng.elasticsearch.dynamic.sql.es;

import io.github.iamazy.elasticsearch.dsl.antlr4.ElasticsearchParser;
import io.github.iamazy.elasticsearch.dsl.sql.model.ElasticDslContext;
import io.github.iamazy.elasticsearch.dsl.sql.parser.QueryParser;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

import java.util.Objects;

/**
 * 替代: io.github.iamazy.elasticsearch.dsl.sql.parser.QueryOrderByParser,解决 order by 生成 model:avg 的问题
 * @author fusheng.zhang
 * @date 2022-02-23 16:33:45
 */
public class QueryOrderByParser implements QueryParser {

    @Override
    public void parse(ElasticDslContext dslContext) {
        if (dslContext.getSqlContext().selectOperation() != null && dslContext.getSqlContext().selectOperation().groupByClause() == null) {
            if (dslContext.getSqlContext().selectOperation().orderClause() != null) {
                ElasticsearchParser.OrderClauseContext orderClauseContext = dslContext.getSqlContext().selectOperation().orderClause();
                for (ElasticsearchParser.OrderContext orderContext : orderClauseContext.order()) {
                    ElasticsearchParser.NameClauseContext nameContext = orderContext.nameClause();
                    if (nameContext instanceof ElasticsearchParser.FieldNameContext) {
                        ElasticsearchParser.FieldNameContext fieldNameContext = (ElasticsearchParser.FieldNameContext) nameContext;
                        String field = fieldNameContext.field.getText();
                        if (fieldNameContext.highlighter != null) {
                            dslContext.getParseResult().getHighlighter().add(field);
                        }
                        SortOrder sortOrder = Objects.isNull(orderContext.ASC()) ? SortOrder.DESC : SortOrder.ASC;
                        SortBuilder<FieldSortBuilder> sortBuilder = SortBuilders.fieldSort(field).order(sortOrder);
                        dslContext.getParseResult().getOrderBy().add(sortBuilder);
                    }
                }
            }
        }
    }
}